package cn.ligoo.part.web.springmvc;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import cn.ligoo.part.domain.UserInfo;
import cn.ligoo.part.service.impl.FacadeImpl;
import cn.ligoo.part.web.Constants;

@Controller
public class LoginController {

	private final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private MessageSource message;

	@Resource
	private FacadeImpl facade;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		logger.debug("...goto login page");
		return "/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
		logger.debug("...login");

		UserInfo t = new UserInfo();
		if (username.indexOf("@") != -1) { // 邮箱
			t.setEmail(username);
		} else { // 工号
			t.setStaff_id(username);
		}
		t.setPassword(password);

		UserInfo userInfo = facade.getUserInfoService().getUserInfo(t);
		if (null == userInfo) {
			String msg = message.getMessage("login.failed", null, null);
			return String.format(Constants.JSON_ERROR, msg);
		}
		WebUtils.setSessionAttribute(request, Constants.SESSION_USER_INFO, userInfo);
		return String.format(Constants.JSON_SUCCESS, null, null);
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		logger.debug("...logout");

		HttpSession session = request.getSession(false);
		if (null != session) {
			session.removeAttribute(Constants.SESSION_USER_INFO);
			session.removeAttribute(Constants.SESSION_THEMES);
			session.invalidate();
		}
		return "/login";
	}
}
